package com.example.springbasicstudy.startupInterface;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <pre>
 * 功能描述：
 * </pre>
 *
 * @author: 李明杰
 * @date: 2023/3/27 11:45
 */
@Component
@Slf4j
public class TimeCostBeanPostProcessor implements BeanPostProcessor {
    private Map<String, Long> costMap = new ConcurrentHashMap<>();

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        costMap.put(beanName, System.currentTimeMillis());
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (costMap.containsKey(beanName)) {
            Long start = costMap.get(beanName);
            long cost = System.currentTimeMillis() - start;
            if (cost > 0) {
                costMap.put(beanName, cost);
                log.error("bean:{}, time:{}", beanName, cost);
            }
        }
        return bean;
    }
}
